<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @row-click="rowClick"
      @darg-sort="sortTable"
      row-key="orgNo"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="openDrawer(t('jggl.khgl.add'))">{{
          $t("jggl.khgl.addCustomer")
        }}</el-button>
        <el-button v-auth="'edit'" type="primary" :icon="Edit" @click="editBtn(scope.selectedList)">{{
          $t("jggl.khgl.edit")
        }}</el-button>
        <el-button v-auth="'add'" type="primary" :icon="Upload" plain @click="batchAdd">{{ $t("jggl.khgl.batchAdd") }}</el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">{{ $t("jggl.khgl.exportData") }}</el-button>
        <el-button v-auth="'delete'" type="danger" :icon="Delete" plain @click="batchDelete(scope.selectedList)">
          {{ $t("jggl.khgl.batchDelete") }}
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" v-auth="'edit'" link :icon="EditPen" @click="openDrawer(t('jggl.khgl.edit'), scope.row)">{{
          $t("jggl.khgl.edit")
        }}</el-button>
        <el-button type="primary" v-auth="'delete'" link :icon="Delete" @click="deleteCustemer(scope.row)">{{
          $t("jggl.khgl.delete")
        }}</el-button>
      </template>
    </ProTable>
    <!-- 附属表格 -->
    <ProTable
      ref="proTableDtl"
      :columns="columnsDtl"
      :request-api="findOrgById"
      :init-param="initParamDtl"
      :data-callback="dataCallbackDtl"
      @darg-sort="sortTable"
    >
    </ProTable>
    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { User, OrgManager } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/custemerDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/jggl/khgl/components/ImportExcel/index.vue";
import UserDrawer from "@/views/jggl/khgl/components/UserDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Edit } from "@element-plus/icons-vue";
import type { TableColumnCtx } from "element-plus/es/components/table/src/table-column/defaults";
import {
  findITSOPUserPager,
  updateITSOPUser,
  deleteITSOPUser,
  batchDeleteITSOPUser,
  addITSOPUser,
  findOrgById,
  ITSOPOrganization,
  importITSOPUser,
  exportITSOPUser
} from "@/api/modules/jggl";

import {
  getUserList,
  deleteUser,
  editUser,
  addUser,
  changeUserStatus,
  resetUserPassWord,
  exportUserInfo,
  BatchAddUser
} from "@/api/modules/user";

import { useI18n } from "vue-i18n";

const { t } = useI18n();

const router = useRouter();

// 跳转详情页
const toDetail = () => {
  router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();
// proTableDtl 实例
const proTableDtl = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});
const initParamDtl = reactive({ page: 1, orgNo: "" });

const dtlList = reactive([]);

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const dataCallbackDtl = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

// 单击行
const rowClick = (row: User.ResUserList, column: TableColumnCtx<OrgManager.ResOrgList>) => {
  initParamDtl.orgNo = row.orgNo;
  proTableDtl.value?.getTableList();
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "orgNo";
  newParams.sord = "desc";
  return findITSOPUserPager(newParams, "itsopUserQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<OrgManager.ResOrgList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

// 表格配置项
const columns = reactive<ColumnProps<OrgManager.ResOrgList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "orgNo", label: t("jggl.khgl.number"), sortable: true },
  {
    prop: "orgName",
    label: t("jggl.khgl.name"),
    width: 180,
    sortable: true,
    search: { el: "input", tooltip: "输入客户名称" },
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.orgName}
        </el-button>
      );
    }
  },
  { prop: "officePhone", label: t("jggl.khgl.phone"), search: { el: "input" }, sortable: true, width: 150 },
  { prop: "email", label: t("jggl.khgl.email"), search: { el: "input" }, sortable: true, width: 150 },
  { prop: "address", sortable: true, label: t("jggl.khgl.address") },
  {
    prop: "technicianNameFullName",
    label: t("jggl.khgl.technician"),
    width: 180,
    sortable: true,
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.technicianNameFullName}
        </el-button>
      );
    }
  },
  // {
  //   prop: "gender",
  //   label: "性别",
  //   // 字典数据（本地数据）
  //   // enum: genderType,
  //   // 字典请求不带参数
  //   enum: getUserGender,
  //   // 字典请求携带参数
  //   // enum: () => getUserGender({ id: 1 }),
  //   search: { el: "select", props: { filterable: true } },
  //   fieldNames: { label: "genderLabel", value: "genderValue" }
  // },
  {
    prop: "typeNo",
    label: t("jggl.khgl.type"),
    sortable: true,
    enum: [
      {
        genderLabel: t("jggl.khgl.freeUser"),
        genderValue: 40
      },
      {
        genderLabel: t("jggl.khgl.paidUser"),
        genderValue: 39
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => <>{scope.row.typeNo === 40 ? t("jggl.khgl.freeUser") : t("jggl.khgl.paidUser")}</>
  },
  { prop: "operation", label: t("jggl.khgl.operation"), fixed: "right", width: 200 }
]);

// 表格配置项
const columnsDtl = reactive<ColumnProps<OrgManager.ResOrgList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  { prop: "userId", label: t("jggl.khgl.id"), sortable: true, width: 60 },
  { prop: "loginName", label: t("jggl.khgl.loginName"), sortable: true, width: 116 },
  { prop: "firstName", label: t("jggl.khgl.firstName"), sortable: true },
  { prop: "lastName", label: t("jggl.khgl.lastName"), sortable: true },
  {
    prop: "orgName",
    label: t("jggl.khgl.organization"),
    width: 180,
    render: scope => {
      return (
        <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
          {scope.row.orgName}
        </el-button>
      );
    }
  },
  { prop: "officePhone", label: t("jggl.khgl.phone"), width: 100 },
  { prop: "phone", label: t("jggl.khgl.mobile") },
  { prop: "email", label: t("jggl.khgl.email"), width: 100 },
  {
    prop: "roles",
    label: t("jggl.khgl.roles"),
    width: 150
  },
  {
    prop: "roles",
    label: t("jggl.khgl.status"),
    width: 80,
    render: scope => <>{scope.row.userState === true ? t("jggl.khgl.enabled") : t("jggl.khgl.disabled")}</>
  }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success(t("jggl.khgl.sortSuccess"));
};

// 删除客户信息
const deleteCustemer = async (params: any) => {
  ElMessageBox.confirm(t("jggl.khgl.confirmDeleteCustomer", { name: params.orgName }), t("jggl.khgl.deleteConfirm"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
    center: true
  })
    .then(() => {
      deleteITSOPUser({ ids: params.orgNo }, "").then(res => {
        ElMessage({
          type: "success",
          message: t("jggl.khgl.deleteSuccess")
        });
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("jggl.khgl.cancelDelete")
      });
    });
};

// 批量删除用户信息
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?ids=" + id[i].orgNo;
    } else {
      idsStr = idsStr + "&ids=" + id[i].orgNo;
    }
    NameStr = NameStr + id[i].orgName + ",";
  }
  ElMessageBox.confirm(t("jggl.khgl.confirmBatchDelete", { names: NameStr }), t("jggl.khgl.deleteConfirm"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
    center: true
  })
    .then(() => {
      batchDeleteITSOPUser(idsStr).then(res => {
        ElMessage({
          type: "success",
          message: t("jggl.khgl.deleteSuccess")
        });
        proTable.value?.clearSelection();
        proTable.value?.getTableList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: t("jggl.khgl.cancelDelete")
      });
    });
};

// 编辑用户信息
const editBtn = async (idList: any[]) => {
  console.log(idList);
  if (idList.length == 1) {
    openDrawer(t("jggl.khgl.edit"), idList[0]);
    proTable.value?.clearSelection();
  } else {
    ElMessage({
      type: "error",
      message: t("jggl.khgl.pleaseSelectOneCustomer")
    });
  }
};

// 重置用户密码
const resetPass = async (params: OrgManager.ResOrgList) => {
  await useHandleData(resetUserPassWord, { id: params.id }, t("jggl.khgl.resetPassword", { username: params.username }));
  proTable.value?.getTableList();
};

// 切换用户状态
const changeStatus = async (row: OrgManager.ResOrgList) => {
  await useHandleData(
    changeUserStatus,
    { id: row.id, status: row.status == 1 ? 0 : 1 },
    t("jggl.khgl.changeStatus", { username: row.username })
  );
  proTable.value?.getTableList();
};

// 导出用户列表
const downloadFile = async () => {
  ElMessageBox.confirm(t("jggl.khgl.confirmExport"), t("jggl.khgl.tips"), { type: "warning" }).then(() =>
    useDownload(exportITSOPUser, t("jggl.khgl.customerList"), proTable.value?.searchParam, true, ".csv")
  );
};

// 批量添加用户
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: t("jggl.khgl.customer"),
    tempApi: ITSOPOrganization,
    importApi: importITSOPUser,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<OrgManager.ResOrgList> = {}) => {
  console.log(title);
  console.log(
    title === t("jggl.khgl.view")
      ? t("jggl.khgl.view")
      : title === t("jggl.khgl.add")
        ? t("jggl.khgl.add")
        : title === t("jggl.khgl.edit")
          ? t("jggl.khgl.edit")
          : ""
  );
  const params = {
    title,
    isView: title === t("jggl.khgl.view"),
    row: { ...row },
    api: title === t("jggl.khgl.add") ? findOrgById : title === t("jggl.khgl.edit") ? findOrgById : findOrgById,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
